<?php
namespace app\common\model;

use app\common\model\User as UserModel;
use app\common\model\DeviceType as DeviceTypeModel;
use app\common\model\Device as DeviceModel;
use app\common\model\Brand as BrandModel;
use app\common\model\BillPayments as BillPaymentsModel;
use app\common\model\FeeTemplate as FeeTemplateModel;
use app\common\model\DeviceLogRepair as DeviceLogRepairModel;
use think\facade\Log;

class DeviceLog extends Common
{
    //时间自动存储
    protected $autoWriteTimestamp = true;
    protected $createTime = 'ctime';
    protected $updateTime = 'utime';
    //软删除位
    protected $deleteTime = 'isdel';
   
    const STATUS_REQSUCCESSED = 1;  //状态 申请使用成功
    const STATUS_REQFAILD = 2;      //状态 申请使用失败
    
    const STATUS_PAYED = 3;         //状态 已支付
    const STATUS_PAYFAILD = 4;      //状态 支付失败
    const STATUS_USED = 5;          //状态 已使用
    const STATUS_REFUND = 6;        //状态 已退款
    
    /**
     * 返回layui的table所需要的格式
     * @author tony
     * @param $post
     * @return mixed
     */
    public function tableData($post)
    {
        if(isset($post['limit'])){
            $limit = $post['limit'];
        }else{
            $limit = config('paginate.list_rows');
        }
        $tableWhere = $this->tableWhere($post);
        $list = $this->alias('log')
            ->field($tableWhere['field'])
            ->join(config('database.prefix') . 'user user', 'log.user_id = user.id', 'left')
            ->join(config('database.prefix') . 'device dev', 'log.device_id = dev.id', 'left')
            ->where($tableWhere['where'])
            ->order($tableWhere['order'])
            ->paginate($limit);

        $data = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型

        $re['code'] = 0;
        $re['msg'] = '';
        $re['count'] = $list->total();
        $re['data'] = $data;

        return $re;
    }

    protected function tableWhere($post)
    { 
        $where = [];
        if(isset($post['user_name']) && $post['user_name'] != ""){
            $where[] = array('user.nickname', 'like', '%'.$post['user_name'].'%');
        }
 
        if(isset($post['bill_id']) && $post['bill_id'] != ""){
            $where[] = array('log.bill_id', 'like', '%'.$post['bill_id'].'%');
        }

        // if(isset($post['device_name']) && $post['device_name'] != ""){
        //     $where[] = array('log.name', 'like', '%'.$post['device_name'].'%');
        // }
        
        if (!empty($post['date'])) {
            $date_string = $post['date'];
            $date_array  = explode(' 到 ', $date_string);
            $sdate       = strtotime($date_array[0] . ' 00:00:00');
            $edate       = strtotime($date_array[1] . ' 23:59:59');
            $where[]     = array('log.ctime', ['>=', $sdate], ['<=', $edate], 'and');
        }

        if(isset($post['status']) && $post['status'] != ""){
            $where[] = array('log.status', 'eq', $post['status']);
        }

        $result['where'] = $where;
        $result['field'] = "log.id, dev.type_id, user.nickname, dev.brand_id, dev.area_id, log.`status`, log.ctime, log.bill_id";
        $result['order'] = 'log.ctime desc';
        return $result;
    }

    /**
     * 根据查询结果，格式化数据
     * @author tony
     * @param $list  array格式的collection
     * @return mixed
     */
    protected function tableFormat($list)
    {
        $deviceType = new DeviceTypeModel();
        $brandModel = new BrandModel();
        $billPaymentsModel = new BillPaymentsModel();
        foreach($list as $k => $v) {
            if($v['type_id']) {
                $list[$k]['typename'] = $deviceType->getNameById($v['type_id']); 
            }
            if($v['brand_id']) {
                $list[$k]['logo'] = $brandModel->getLogoById($v['brand_id']);
            }
            if($v['area_id']) {
                $list[$k]['area'] = get_area($v['area_id']);
            }
            if($v['status']) {
                $list[$k]['status'] = $this->getStatusName($v['status']);
            }
            if($v['ctime']) { 
                $list[$k]['ctime'] = getTime($v['ctime']);
            }
            if($v['bill_id']) {
                $list[$k]['money'] = $billPaymentsModel->getMoneyById($v['bill_id']);
            } 
        }
        return $list;
    }

    /**
     * 支付
     * @param string $device_id
     * @param string $name
     * @param string $pay_params 
     * @return mixed
     */
    public function pay($money_id, $user_id, $device_id, $name, $pay_params){
        $result = ['status' => true, 'msg' => '支付成功' , 'data' => ''];

        // 设备启动参数有效性检测
        $device = \org\Device::create($pay_params['cat_name'], $pay_params['brand_name'], $pay_params['type_name'], $pay_params);      
        $checkResult = $device->checkConfig();

        if(!$checkResult['status']) {
            return error_code(10003);
        }

        //判断是否有足够的资金用于支付 
        $userModel = new UserModel();
        $userInfo = $userModel->getUserInfo($user_id);
        if(ncPriceCalculate($userInfo['balance'], '+', $userInfo['bindingbalance']) < $pay_params['money']) {
            $result['status']  = false;
            $result['msg']   = '余额不足';
            return $result;
        }
 
        // 申请使用设备
        $reqResult = $device->start();
        if(!$reqResult['status']) {
            $data['status']         = DeviceLog::STATUS_REQFAILD;
            $data['bill_id']        = '';
            $result = $reqResult;
        } else { 
            $data['status']         = DeviceLog::STATUS_REQSUCCESSED;

            //生成支付单,并发起支付
            $billPaymentsModel = new BillPayments();
            $billPaymentInfo = $billPaymentsModel->pay($money_id, 'balancepay', $user_id, BillPayments::TYPE_DEVICE_PAY, $pay_params);
            // 保存启动记录
            if(!$billPaymentInfo) {
                $data['status']         = DeviceLog::STATUS_PAYFAILD;
                $data['bill_id']        = '';
                $result = $reqResult;
            } else { 
                $data['status']         = DeviceLog::STATUS_PAYED;
                $result['data']['url'] = urldecode($reqResult['data']['result']);
                $result['data']['balance'] = $billPaymentInfo['data']['balance'];
                $result['data']['bindingbalance'] = $billPaymentInfo['data']['bindingbalance'];
                $data['bill_id']        = $billPaymentInfo['data']['payment_id'];
            }
        }

        $useParams = [
            'times' => 0
        ];

        // 保存设备使用记录
        $data['user_id']        = $user_id;
        $data['device_id']      = $device_id;
        $data['name']           = $name;
        $data['pay_params']     = json_encode($pay_params);   
        $data['result_params']  = json_encode($reqResult);    
        $data['use_params']     = json_encode($useParams);   
        $this->save($data);

        $result['data']['log_id'] = $this->id;
        return $result; 
    } 
 
    /**
     * 吹风机声波播放
     * @return array
     */
    public function blowerPlay($id)
    {
        $result = ['status' => true, 'msg' => '' , 'data' => ''];
        $logInfo = $this->where(['id' => $id])->find();

        if(!$logInfo) {
            return error_code(10002);
        }
  
        $use_params = json_decode($logInfo['use_params'], true);
        $use_params['times'] = $use_params['times'] + 1;
        $data['use_params']     = json_encode($use_params);   
        
        $this->save($data, [
            'id' => $id,
        ]);

        return $result;
    }

    /**
     * 获取设备启动日志微信小程序
     * @param $input
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getDeviceLog($input)
    {
        $where = [];
        if (!empty($input['type_id'])) {
            $where[] = array('dev.type_id', 'eq', $input['type_id']);
        }
        if (!empty($input['user_id'])) {
            $where[] = array('log.user_id', 'eq', $input['user_id']);
        }
  
        $page  = $input['page'] ? $input['page'] : 1;
        $limit = $input['limit'] ? $input['limit'] : 20;

        $data = $this->alias('log')
            ->field('log.id, dev.type_id, user.nickname, dev.brand_id, dev.area_id, log.`status`, log.ctime, log.bill_id')
            ->join(config('database.prefix') . 'user user', 'log.user_id = user.id', 'left')
            ->join(config('database.prefix') . 'device dev', 'log.device_id = dev.id', 'left')
            ->where($where)
            ->order('log.ctime desc')
            ->page($page, $limit)
            ->select();

        $count = $this->alias('log')
            ->field('log.id, dev.type_id, user.nickname, dev.brand_id, dev.area_id, log.`status`, log.ctime, log.bill_id')
            ->join(config('database.prefix') . 'user user', 'log.user_id = user.id', 'left')
            ->join(config('database.prefix') . 'device dev', 'log.device_id = dev.id', 'left')
            ->where($where)
            ->order('log.ctime desc')
            ->count();

        $deviceType = new DeviceTypeModel();
        $brandModel = new BrandModel();
        $billPaymentsModel = new BillPaymentsModel();

        if(!$data->isEmpty())
        {
            foreach($data as $key => $val)
            {
                if($val['type_id']) {
                    $data[$key]['typename'] = $deviceType->getNameById($val['type_id']); 
                }
                if($val['brand_id']) {
                    $data[$key]['logo'] = $brandModel->getLogoById($val['brand_id']);
                }
                if($val['area_id']) {
                    $data[$key]['area'] = get_area($val['area_id']);
                }
                if($val['status']) {
                    $data[$key]['status'] = $this->getStatusName($val['status']);
                }
                if($val['ctime']) { 
                    $data[$key]['ctime'] = getTime($val['ctime']);
                }
                if($val['bill_id']) {
                    $data[$key]['money'] = $billPaymentsModel->getMoneyById($val['bill_id']);
                }
            }
        }

        return array('data' => $data, 'count' => $count);
    } 
 
    /**
     * 获取状态名称
     * @param $id
     * @return string
     */
    private function getStatusName($id) 
    {
        $res = "";
        switch ($id){
            case DeviceLog::STATUS_REQSUCCESSED:
                $res = "申请成功";
            break;
            case DeviceLog::STATUS_REQFAILD:
                $res = "申请失败";
            break;
            case DeviceLog::STATUS_PAYED:
                $res = "支付成功";
            break;
            case DeviceLog::STATUS_PAYFAILD:
                $res = "支付失败";
            break;
            case DeviceLog::STATUS_USED:
                $res = "已使用";
            break;
            case DeviceLog::STATUS_REFUND:
                $res = "已退款";
            break;
            default:
                $res = "";
            break;
        }
        return $res;
    }

    /**
     * 获取设备使用详情
     * @return array
     */
    public function getDeviceLogInfo($id)
    {
        $result = ['status' => true, 'msg' => '' , 'data' => ''];
        $logInfo = $this->where(['id' => $id])->find();

        if(!$logInfo) {
            return error_code(10002);
        }

        $billPaymentsModel = new BillPaymentsModel();
        $deviceModel = new DeviceModel(); 
        $feeTemplateModel = new FeeTemplateModel();
        $deviceLogRepairModel = new DeviceLogRepairModel();
       
        // 补齐信息
        $deviceInfo = $deviceModel->getDeviceInfo($logInfo['device_id']);
        $options = $feeTemplateModel->getDeviceOptionsByParams($deviceInfo['data']['cat_id'], $deviceInfo['data']['brand_id'], $deviceInfo['data']['sub_id'], true);
        $deviceRepairLog = $deviceLogRepairModel->getDeviceRepairInfo($logInfo['bill_id']);

        $repair_id = '';
        if($deviceRepairLog['data']){
            $repair_id = $deviceRepairLog['data']['repair_id'];
        }

        $logInfo['area'] = get_area($deviceInfo['data']['area_id']);
        $logInfo['status'] = $this->getStatusName($logInfo['status']);
        $logInfo['ctime'] = date('Y-m-d H:i:s', $logInfo['ctime']);
        $logInfo['money'] = $billPaymentsModel->getMoneyById($logInfo['bill_id']);
 
        $result_params = json_decode($logInfo['result_params'], true); 
        $pay_params = json_decode($logInfo['pay_params'], true); 
        
        foreach ($options['data']['fee'][0]['value'] as $key => $val) {
            if ($pay_params['mins'] == $val['value']) { 
                $logInfo['min'] = $val['name'];
                break;
            }
        }

        foreach ($options['data']['ctrl'][0]['value'] as $key => $val) {
            if ($pay_params['channels'] == $val['value']) { 
                $logInfo['channel'] = $val['name'];
                break;
            }
        }

        $logInfo['url'] = urldecode($result_params['data']['result']);
        $logInfo['repair_id'] = $repair_id;
        $result['data'] = $logInfo; 
        return $result;
    }
}
